<template>
  <div class="facility-inspection">
    <div class="header">
      <router-link to="/main/wuye/facility/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>设施巡检</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增巡检</el-button>
      </div>
    </div>

    <div class="content">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="待巡检" name="pending">
          <el-table :data="pendingList" style="width: 100%">
            <el-table-column prop="deviceNo" label="设备编号" width="180"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" width="150"></el-table-column>
            <el-table-column prop="location" label="设备位置" width="180"></el-table-column>
            <el-table-column prop="inspectionType" label="巡检类型" width="120"></el-table-column>
            <el-table-column prop="lastInspection" label="上次巡检" width="180"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
                <el-button size="mini" type="primary" @click="startInspection(scope.row)">巡检</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已巡检" name="completed">
          <el-table :data="completedList" style="width: 100%">
            <el-table-column prop="deviceNo" label="设备编号" width="180"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" width="150"></el-table-column>
            <el-table-column prop="inspector" label="巡检人" width="120"></el-table-column>
            <el-table-column prop="inspectionTime" label="巡检时间" width="180"></el-table-column>
            <el-table-column prop="status" label="设备状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 详情对话框 -->
    <el-dialog title="设备巡检详情" :visible.sync="detailDialogVisible" width="60%">
      <div class="device-detail" v-if="currentDevice">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="设备编号">{{ currentDevice.deviceNo }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ currentDevice.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备位置">{{ currentDevice.location }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ currentDevice.deviceType }}</el-descriptions-item>
          <el-descriptions-item label="生产厂家">{{ currentDevice.manufacturer }}</el-descriptions-item>
          <el-descriptions-item label="安装日期">{{ currentDevice.installDate }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section" v-if="currentDevice.inspectionHistory">
          <h4>巡检记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in currentDevice.inspectionHistory"
              :key="index"
              :type="getTimelineType(record.status)"
              :timestamp="record.time">
              {{ record.inspector }} 进行了{{ record.type }}巡检
              <p class="inspection-result">状态：{{ record.status }}</p>
              <p v-if="record.remark" class="inspection-remark">备注：{{ record.remark }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 巡检表单对话框 -->
    <el-dialog title="设备巡检" :visible.sync="inspectionDialogVisible" width="50%">
      <el-form :model="inspectionForm" label-width="100px">
        <el-form-item label="巡检项目">
          <el-checkbox-group v-model="inspectionForm.items">
            <el-checkbox label="外观检查">外观检查</el-checkbox>
            <el-checkbox label="性能测试">性能测试</el-checkbox>
            <el-checkbox label="安全检查">安全检查</el-checkbox>
            <el-checkbox label="清洁保养">清洁保养</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="设备状态">
          <el-radio-group v-model="inspectionForm.status">
            <el-radio label="正常">正常</el-radio>
            <el-radio label="异常">异常</el-radio>
            <el-radio label="待维修">待维修</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="检查结果">
          <el-input type="textarea" v-model="inspectionForm.result" rows="4"></el-input>
        </el-form-item>

        <el-form-item label="处理建议" v-if="inspectionForm.status !== '正常'">
          <el-input type="textarea" v-model="inspectionForm.suggestion" rows="4"></el-input>
        </el-form-item>

        <el-form-item label="上传照片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="inspectionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitInspection">提交巡检</el-button>
      </div>
    </el-dialog>

    <!-- 新增巡检对话框 -->
    <el-dialog title="新增巡检任务" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addForm" ref="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="巡检区域" prop="area">
          <el-select v-model="addForm.area" placeholder="请选择巡检区域">
            <el-option label="办公区" value="办公区"></el-option>
            <el-option label="生产区" value="生产区"></el-option>
            <el-option label="仓储区" value="仓储区"></el-option>
            <el-option label="公共区域" value="公共区域"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="巡检类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择巡检类型">
            <el-option label="日常巡检" value="日常巡检"></el-option>
            <el-option label="安全巡检" value="安全巡检"></el-option>
            <el-option label="设备巡检" value="设备巡检"></el-option>
            <el-option label="专项巡检" value="专项巡检"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="巡检时间" prop="inspectionTime">
          <el-date-picker
            v-model="addForm.inspectionTime"
            type="datetime"
            placeholder="选择巡检时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="巡检人员" prop="inspector">
          <el-select v-model="addForm.inspector" placeholder="请选择巡检人员">
            <el-option
              v-for="item in inspectorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="巡检内容" prop="content">
          <el-input
            type="textarea"
            v-model="addForm.content"
            rows="3"
            placeholder="请输入巡检内容描述">
          </el-input>
        </el-form-item>
        
        <el-form-item label="注意事项" prop="notes">
          <el-input
            type="textarea"
            v-model="addForm.notes"
            rows="2"
            placeholder="请输入注意事项">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'pending',
      pendingList: [
        {
          deviceNo: 'SB202403001',
          deviceName: '中央空调主机',
          location: 'A栋-设备间',
          deviceType: '空调设备',
          manufacturer: 'XX品牌',
          installDate: '2023-01-01',
          inspectionType: '日常巡检',
          lastInspection: '2024-03-10'
        }
      ],
      completedList: [],
      detailDialogVisible: false,
      inspectionDialogVisible: false,
      currentDevice: null,
      inspectionForm: {
        items: [],
        status: '正常',
        result: '',
        suggestion: ''
      },
      addDialogVisible: false,
      submitting: false,
      addForm: {
        area: '',
        type: '',
        inspectionTime: '',
        inspector: '',
        content: '',
        notes: ''
      },
      addRules: {
        area: [
          { required: true, message: '请选择巡检区域', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择巡检类型', trigger: 'change' }
        ],
        inspectionTime: [
          { required: true, message: '请选择巡检时间', trigger: 'change' }
        ],
        inspector: [
          { required: true, message: '请选择巡检人员', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入巡检内容', trigger: 'blur' },
          { min: 10, message: '巡检内容不能少于10个字符', trigger: 'blur' }
        ]
      },
      inspectorOptions: [
        { label: '张工', value: '张工' },
        { label: '李工', value: '李工' },
        { label: '王工', value: '王工' }
      ]
    }
  },
  methods: {
    getStatusType(status) {
      const map = {
        '正常': 'success',
        '异常': 'warning',
        '待维修': 'danger'
      }
      return map[status] || 'info'
    },
    getTimelineType(status) {
      return status === '正常' ? 'success' : 'warning'
    },
    viewDetail(row) {
      this.currentDevice = row
      this.detailDialogVisible = true
    },
    startInspection(row) {
      this.currentDevice = row
      this.inspectionForm = {
        items: [],
        status: '正常',
        result: '',
        suggestion: ''
      }
      this.inspectionDialogVisible = true
    },
    submitInspection() {
      if (!this.inspectionForm.items.length || !this.inspectionForm.result) {
        this.$message.error('请填写完整的巡检信息')
        return
      }

      // TODO: 提交巡检信息到后端
      const inspectionRecord = {
        time: new Date().toLocaleString(),
        inspector: '当前用户',
        type: '日常',
        status: this.inspectionForm.status,
        remark: this.inspectionForm.result
      }

      this.currentDevice.inspectionHistory = this.currentDevice.inspectionHistory || []
      this.currentDevice.inspectionHistory.unshift(inspectionRecord)

      // 从待巡检列表移动到已巡检列表
      const index = this.pendingList.findIndex(item => item.deviceNo === this.currentDevice.deviceNo)
      if (index > -1) {
        const device = { ...this.currentDevice }
        device.inspector = inspectionRecord.inspector
        device.inspectionTime = inspectionRecord.time
        device.status = inspectionRecord.status
        this.pendingList.splice(index, 1)
        this.completedList.unshift(device)
      }

      this.$message.success('巡检提交成功')
      this.inspectionDialogVisible = false
    },
    handleAdd() {
      this.addDialogVisible = true;
      this.addForm = {
        area: '',
        type: '',
        inspectionTime: '',
        inspector: '',
        content: '',
        notes: ''
      };
    },
    submitAdd() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true;
            
            // 构造新的巡检任务数据
            const newInspection = {
              inspectionNo: this.generateInspectionNo(),
              ...this.addForm,
              status: '待巡检'
            };
            
            // TODO: 调用后端API保存数据
            // await this.$http.post('/api/facility-inspection/add', newInspection);
            
            // 添加到待巡检列表
            this.pendingList.unshift(newInspection);
            
            this.$message.success('新增巡检任务成功');
            this.addDialogVisible = false;
          } catch (error) {
            this.$message.error('新增失败：' + error.message);
          } finally {
            this.submitting = false;
          }
        }
      });
    },
    generateInspectionNo() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
      return `XJ${year}${month}${day}${random}`;
    }
  }
}
</script>

<style lang="scss" scoped>
.facility-inspection {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .header-actions {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .detail-section {
    margin-top: 20px;

    h4 {
      margin: 0 0 10px;
      color: #303133;
    }

    .inspection-result {
      margin: 5px 0 0;
      color: #606266;
    }

    .inspection-remark {
      margin: 5px 0 0;
      font-size: 13px;
      color: #909399;
    }
  }
}
</style> 